package com.kylin.cf;

import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;

public class SpecMysqlCf {

  public static void main(String[] args) throws TasteException {

    init();

    MysqlDataSource dataSource = new MysqlDataSource();
    dataSource.setServerName("115.29.140.3");
    dataSource.setUser("root");
    dataSource.setPassword("root");
    dataSource.setDatabaseName("febs_spark_wc");

    System.out.println("加载评分数据。。。");
    DataModel model = new MySQLJDBCDataModel(dataSource, "book_ratings_tmp", "User_ID", "book_id",
        "Book_Rating", null);//数据模型
    System.out.println("评分数据加载完成， 计算推荐结果。。。");
    ItemSimilarity item = new PearsonCorrelationSimilarity(model);//用户相识度算法
    Recommender r = new GenericItemBasedRecommender(model, item);//物品推荐算法
    LongPrimitiveIterator iter = model.getUserIDs();
    int count = 0;
    while (count < 10 && iter.hasNext()) {
      long uid = iter.nextLong();
      List<RecommendedItem> list = r.recommend(uid, 10);
      System.out.printf("uid:%s", uid);
      for (RecommendedItem ritem : list) {
        System.out
            .printf("(book id: %s,recommend rate: %f)", ritem.getItemID(), ritem.getValue());
      }
      System.out.println();
      count++;
    }
  }

  public static void init() {
    String url = "jdbc:mysql://115.29.140.3:3306/febs_spark_wc";
    String username = "root";
    String password = "root";
    Connection conn = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(url, username, password);

      Statement statement = conn.createStatement();
      statement.execute("drop table book_ratings_tmp");

      statement.execute(
          "create table book_ratings_tmp as "
              + "select * from book_ratings ORDER BY rating_time desc limit 10000");
      System.out.println("数据准备完成。");

    } catch (SQLException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
